from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, JsonResponse
from libs.captcha.captcha import captcha
from libs.rl_sms import send_message
from redis import StrictRedis
import random


# 生成图形验证码
class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 生成图片,及答案
        text, image = captcha.generate_captcha()

        # 保存答案和uuid到redis中
        client = StrictRedis()  # 127.0.0.1 6379
        client.set(uuid, text)

        return HttpResponse(image, content_type='image/jpeg')
        pass


# 发送短信验证码
class SMSCodeView(View):
    '''短信验证码'''
    def get(self, request, mobile):
        # 接收参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验参数
        if not all([mobile, image_code, uuid]):
            return JsonResponse({'msg': '缺少参数', 'code': '999'})
        # 判断图形验证码
        # 1. 从redis取
        client = StrictRedis()
        redis_image_code = client.get(uuid)
        # 2. 从redis删除
        client.delete(uuid)
        # 3. 对比
        if redis_image_code:
            redis_image_code = redis_image_code.decode()  # 将二进制转化为字符
        else:
            redis_image_code = None
        if image_code.upper() == redis_image_code:
            pass
        else:
            return JsonResponse({'code': '999', 'msg': '图形验证码不正确'})
        # 生成短信验证码
        sms_code = '%04d'%random.randint(0, 9999)  # 生成随机数0000 -> 9999
        # 把短信存到redis中
        client.setex(mobile, 5 * 60, sms_code)
        # 发送短信验证码
        send_message(mobile, sms_code, '5')
        # 13546493199
        return JsonResponse({'code': '0', 'msg': 'ok'})
